﻿@{
    //var messageModal = (MessageModalVM) ViewBag.MessageModal;
    string hostPart = Request.ServerVariables["HTTP_HOST"];
    string prefixPart = !string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["SubSystem"]) && Request.ServerVariables["SERVER_PORT"] == "80" ? "/" + System.Configuration.ConfigurationSettings.AppSettings["SubSystem"] : "";
     
    string urlEss = string.Format("{0}://{1}{2}{3}",
                                    Request.Url.Scheme,
                                    (Request.Url.Authority != "localhost:60830" ? Request.Url.Authority : "localhost:30743"), 
                                    prefixPart,
                                    (Request.Url.Authority != "localhost:60830" ? "/ESS":"") + "/App_UI/Forms/TaskListsPopUp.aspx?tokenKey=");
}
<script>

    //function addCommasBase(nStr) {
    //    x = nStr.split('.');
    //    x1 = x[0];
    //    x2 = x.length > 1 ? '.' + x[1] : '';
    //    var rgx = /(\d+)(\d{3})/;
    //    while (rgx.test(x1)) {
    //        x1 = x1.replace(rgx, '$1' + /*',' + */'$2');
    //    }
    //    return x1 + x2;
    //}
    function addCommasOnly(nStr) {
        return nStr;
        //nStr += '';
        //return addCommasBase(nStr);
    }
    function addCommas(nStr) {
        return nStr;
        //nStr += '';
        //nStr = parseFloat(nStr).toFixed(2);
        //return addCommasBase(nStr);
    }

    function createFrame(url) {
        try {
            if (document.getElementById("extenalLink") !== null) {
                var d = document.getElementById("frameZone");
                d.removeChild(document.getElementById("extenalLink"));
            } else {
            }

            var iframe = document.createElement("iframe"); //create iframe
            iframe.id = "extenalLink"; //name
            iframe.src = url; //"Widget/Twitter/LockBackground.html"; //location
            iframe.style.backgroundColor = "transparent"; //transbg
            iframe.frameBorder = "0"; //no border
            iframe.allowTransparency = "true"; //allow trans
            iframe.width = '100%';
            // iframe.style.height = '95%';
            d = document.getElementById("frameZone"); //grab div to connect to iframe
            d.appendChild(iframe); //connect
            // alert((parent.document.body.clientHeight - 150) + 'px');

            iframe = null;
            d = null;
            var clientHeight = (500);
            $('#extenalLink').height(clientHeight + 'px');
        } catch (e) {
            alert("Exception e createFrame:" + e);
        }
    }

    function removeIframe() {
        try {
            var iframe = document.getElementById("extenalLink");
            iframe.src = ""; //clear
            iframe = null; //clear
            var d = document.getElementById("frameZone");
            d.removeChild(document.getElementById("extenalLink"));
        } catch (e) {
            alert("Exception e removeIframe:" + e);
        }
    }

    function OpenTaskList() {
        // this item is on /Shared/_ModalMessage.cshtml
        $('#windowTaskList').modal('show');
    }
    
    $(function () {

        $('#windowTaskList').on("hidden", function(e) {
            $('#windowTaskList').css('z-index', -1000000);
            removeIframe();
        });

        $('#windowTaskList').on("show", function(e) {
            $('#windowTaskList').css('z-index', 1000000);
            $('#windowTaskList').css('color', 'white');
            $('#windowTaskList').css('background-color', 'rgb(105, 138, 191)');


            $.ajax({
                url: '@Url.Action("GenNewOtpTokenKey", "Home")',
                data: { 'height': $(document).height() },
                type: "post",
                cache: false,
                success: function (tokenKey) {
                    createFrame('@urlEss' + tokenKey);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert("Error encountered while tranfering to TaskListPopup.");
                }
            });
        });

        $(".chzn-select").chosen({ width: '220px' });
        $(".chzn-select").each(function () {
            var manualwidth = $(this).data('manualwidth');
            if (manualwidth == undefined) { 
                return;
            } else {
                $(this).next(".chzn-container").css('width', manualwidth); 
            }
        });
        $(".chzn-select-deselect").chosen({ allow_single_deselect: true });
        $(".date-picker").each(function(index) {
            var util = new gerpUtility();
            var dateObj = util.convertStringToDate(this.value);
            this.value = util.getDatePickerStringFormat(dateObj);
        });
        var tableIdOfExportButton = function(v) {
            return v.parent().parent().parent().parent().parent().next().find('table').attr('id');
        };

        $('.excelExportLink').on('click', function() {
            changeTableLengthToMax();
            tableToExcel(tableIdOfExportButton($(this)));
        });

        $('.wordExportLink').on('click', function() {
            changeTableLengthToMax();
            tableToWord(tableIdOfExportButton($(this)));
        });

        $('.pdfExportLink').on('click', function() {
            changeTableLengthToMax();
            tableToPdf('asdf', 'pdf1');
        });

        var changeTableLengthToMax = function() {
            // not work 
            // $("select[name='table_length']").val("-1");
        };

        var tableToPdf;

        $(function() {

            var specialElementHandlers = {
                '#editor': function(element, renderer) {
                    return true;
                }
            };

            tableToPdf = (function(divId, filename) {
                var doc = new jsPDF();
                doc.fromHTML($('#' + divId).html(), 15, 15, {
                    'width': 170,
                    'elementHandlers': specialElementHandlers
                });
                doc.save(filename + '.pdf');
            });
        });
                        @* $('td').truncate({ max_length: '@(GimsConfigReader.TableCellIndexLimitChar??"100")' });*@
         
                @*@if(ViewBag.NoLayout != true && ViewBag.EmptyLayout != true)
        {
            //@:alert('view bag no layout != true, url = @Request.RawUrl' );
                            int unreadMessageAmount = new KPIS.GERP.WEB.GIMS.SysMessageService.SysMessageServiceClient().GetUnreadCount(GimsMembership.CurrentEmpId);
            if (unreadMessageAmount > 0)
            {
                @:alert('มีข้อความใหม่ @unreadMessageAmount ข้อความ @Request.RawUrl');
            }
        } else
        {
            //@:alert('view bag no layout = true, url = @Request.RawUrl');
        }*@
        $('#SearchKeyword').bind('keypress', function (e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                window.location = '@Url.Action("SearchKeywords", "Search")?keywords=' + $('#SearchKeyword').val();
            } 
        });
        $("#iconClickRefreshPopup").click(function (e) {
            if ($('#extenalLink') !== undefined) {
                $('#extenalLink').attr('src', function(i, val) { return val; });
            }
        });
        
        // End Document.Ready
    });
	 
    @if(ViewBag.UnWarnCount != null && ViewBag.UnWarnCount as int? > 0)
    {
        <text>
            $(document).ready(function(){
                $('#popupMessage').modal('show');
            });
        </text>
    }
    
    @{
        int selectedCategory = ViewBag.selectedCategory ?? 1;
    }

    $('#treeCategoryApproveRequire').ace_tree({
        dataSource: treeDataSourceApproveRequire,
        multiSelect: false,
        loadingHTML: '<div class="offset1"><i class="icon-refresh icon-spin blue"></i></div>',
        'open-icon': 'icon-folder-open',
        'close-icon': 'icon-folder-close',
        'selectable': true,
        'selected-icon': null,
        'unselected-icon': null
    });

    $('#treeCategoryMyApproveRequire').ace_tree({
        dataSource: treeDataSourceMyApproveRequire,
        multiSelect: false,
        loadingHTML: '<div class="offset1"><i class="icon-refresh icon-spin blue"></i></div>',
        'open-icon': 'icon-folder-open',
        'close-icon': 'icon-folder-close',
        'selectable': true,
        'selected-icon': null,
        'unselected-icon': null
    });

    $('#treeCategoryApproveRequire').on('selected', function (evt, data) {
        var id = data['info']['0']['id'];
        window.location.href = '@Url.Action("Index", "Task")?selectedCategory=' + id;
    });

    @if (selectedCategory == 2)
    {
        @:$("div.tree-item:contains('คำขอที่ฉันขอ')").addClass("tree-selected");
    }
    else if (selectedCategory == 3)
    {
        @:$("div.tree-item:contains('คำขอที่ตอบกลับไป')").addClass("tree-selected");
    }
    else if (selectedCategory == 4)
    {
        @:$("div.tree-item:contains('คำขอที่ยกเลิก')").addClass("tree-selected");
    }
    else
    {
        @:$("div.tree-item:contains('คำขอที่ส่งเข้ามา')").addClass("tree-selected");
    }
    $('#treeCategoryMyApproveRequire').on('selected', function (evt, data) {
        var id = data['info']['0']['id'];
        window.location.href = '@Url.Action("Index", "Task")?selectedCategory=' + id;
    });

    @if (selectedCategory == 2)
    {
        @:$("div.tree-item:contains('คำขอที่ฉันขอ')").addClass("tree-selected");
    }
    else if (selectedCategory == 3)
    {
        @:$("div.tree-item:contains('คำขอที่ตอบกลับไป')").addClass("tree-selected");
    }
    else if (selectedCategory == 4)
    {
        @:$("div.tree-item:contains('คำขอที่ยกเลิก')").addClass("tree-selected");
    }
    else
    {
        @:$("div.tree-item:contains('คำขอที่ส่งเข้ามา')").addClass("tree-selected");
    }
</script> 